package com.tanhua.admin.service;


import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.admin.exception.BusinessException;
import com.tanhua.commons.utils.Constants;
import com.tanhua.dubbo.api.CommentApi;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.enums.CommentType;
import com.tanhua.model.mongo.Comment;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.CommentVo;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ManagerService {

     @DubboReference
     private UserInfoApi userInfoApi;
     @DubboReference
     private VideoApi videoApi;
     @DubboReference
     private MovementApi movementApi;
     @DubboReference
     private CommentApi commentApi;

     @Autowired
     private RedisTemplate<String,String> redisTemplate;

    /**
     * 分页查询
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult findAllUsers(Integer page, Integer pagesize) {
        IPage<UserInfo> iPage= userInfoApi.findAll(page,pagesize);
        List<UserInfo> list =iPage.getRecords();
        for (UserInfo userInfo : list) {
            String key=Constants.USER_FREEZE+userInfo.getId();
            if(redisTemplate.hasKey(key)){
                userInfo.setUserStatus("2");
            }
        }
        return new PageResult(page,pagesize,iPage.getTotal(),iPage.getRecords());
    }

    //根据id查询
    public UserInfo findUserById(Long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        //查询redis中的冻结状态
        String key=Constants.USER_FREEZE+userId;
        if(redisTemplate.hasKey(key)){
            userInfo.setUserStatus("2");
        }
        return userInfo;
    }

    //根据用户id分页查询此用户发布的所有视频列表
    public PageResult findAllVideos(Integer page, Integer pagesize, Long uid) {
        return videoApi.findByUserId(page,pagesize,uid);
    }

    //查询动态列表
    public PageResult findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {
        //调用api查询数据 movement对象
        PageResult result=movementApi.findByUserId(uid,state,page,pagesize);
        //解析pageresult 提取出movement对象
        List<Movement> items = ( List<Movement>)result.getItems();

        if(CollUtil.isEmpty(items)){
            return new PageResult();
        }
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(userIds, null);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : items) {
            UserInfo userInfo=map.get(movement.getUserId());
            if(userInfo!=null){
                MovementsVo vo =MovementsVo.init(userInfo,movement);
                vos.add(vo);
            }
        }
        //构造返回值
        result.setItems(vos);
        return result;
    }

    /**
     * 用户冻结
     * @param params
     * @return
     */
    public Map userFreeze(Map params) {
        //构造key
        String userId=params.get("userId").toString();
        String key = Constants.USER_FREEZE+userId;
        //构造失效时间
        Integer freezingTime=Integer.valueOf( params.get("freezingTime").toString());
        int days = 0;
        if (freezingTime == 1) {
            days = 3;
        }
        if (freezingTime == 2) {
            days = 7;
        }
        if (freezingTime == 3) {
            days = -1;
        }
        //将数据存入redis
        String value = JSON.toJSONString(params);
        if(days>0){
            redisTemplate.opsForValue().set(key,value,days, TimeUnit.MINUTES);//TODO 本来应该是天，但是此处为了方便测试为分钟
        }else{
            redisTemplate.opsForValue().set(key,value);
        }
        Map map = new HashMap();
        map.put("message","冻结成功");
        return map;
    }

    /**
     * 用户解冻
     * @param params
     * @return
     */
    public Map userUnfreeze(Map params) {
        String userId = params.get("userId").toString();
        String reasonsForThawing = (String) params.get("reasonsForThawing");
        redisTemplate.delete(Constants.USER_FREEZE+userId);
        Map map = new HashMap();
        map.put("message","解冻成功");
        return map;
    }

    //查询动态详情
    public MovementsVo movementDetail(String id) {
        Movement movement =movementApi.findById(id);
        UserInfo userInfo=userInfoApi.findById(movement.getUserId());
        if(userInfo == null){
            throw new BusinessException("用户信息异常");
        }
        MovementsVo vo =MovementsVo.init(userInfo,movement);
        return vo;
    }
    //查询动态的评论 分页展示
    public PageResult comments(String messageID, Integer page, Integer pagesize) {
        PageResult pr=commentApi.findCommentByPage(messageID, CommentType.COMMENT,page,pagesize);
        List<Comment> comments= (List<Comment>) pr.getItems();
        if(comments.isEmpty()){
            return new PageResult();
        }
        List<Long> userIds =CollUtil.getFieldValues(comments,"userId",Long.class);
        Map<Long,UserInfo> map =userInfoApi.findByIds(userIds,null);
        List<CommentVo> voList = new ArrayList<>();
        for (Comment comment : comments) {
            UserInfo userInfo=map.get(comment.getUserId());
            if(userInfo!=null){
                CommentVo vo =CommentVo.init(userInfo,comment);
                voList.add(vo);
            }
        }
        pr.setItems(voList);
        return pr;
    }

    //动态审核通过
    public void pass(List<String> params) {
        if(params == null){
            throw new BusinessException("请选择文章！");
        }
        for (String movementId : params) {
            movementApi.update(movementId,1);
        }
    }

    //动态审核拒绝
    public void reject(List<String> params) {
        if(params == null){
            throw new BusinessException("请选择文章！");
        }
        for (String movementId : params) {
            movementApi.update(movementId,2);
        }

    }
}
